package com.example.app.pages.main.home.addNew.addRecord

import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import com.example.app.R
import com.example.app.addNewViewModel
import com.example.app.addRecordViewModel
import com.example.app.barStateViewModel
import com.example.app.cls.MyState
import com.example.app.components.MyBottomAppBar.MyBottomAppBar
import com.example.app.components.MyButton.MyOutlinedButton
import com.example.app.components.MyButton.MyTextButton
import com.example.app.components.MyIcon.MyDoneIcon
import com.example.app.components.MyIcon.MyDownIcon
import com.example.app.components.MyIcon.MyNavigationIcon
import com.example.app.components.MyImage.MyFitImage
import com.example.app.components.MyModalBottomSheet.MyCustomModalBottomSheet
import com.example.app.components.MyScaffold.MyScaffoldHasTipAndLoading
import com.example.app.components.MySpacer.MySpacer
import com.example.app.components.MyText.MyText
import com.example.app.components.MyTopBar.MyTopBar
import com.example.app.mainViewModel
import com.example.app.myMapSelectedState
import com.example.app.pages.main.home.addNew.addRecord.viewModel.AddRecordViewModel
import com.example.app.pages.main.home.me.viewModel.AccountType
import com.example.app.pages.main.home.me.viewModel.AddNewViewModel
import com.example.app.routeViewModel
import com.example.app.viewmodel.BarStateViewModel
import com.example.app.viewmodel.MainViewModel
import com.example.app.viewmodel.RouteViewModel
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState

class AddRecordState : MyState() {
}
@OptIn(
    ExperimentalMaterial3Api::class,
    ExperimentalPagerApi::class
)
@Composable
fun AddRecord(
) {
    var context = LocalContext.current
    var windowWidth = with(LocalDensity.current) {
        LocalConfiguration.current.screenWidthDp
    }
    var allCats = addRecordViewModel.allCats.collectAsState()
    var allTitles = addRecordViewModel.allTitles.collectAsState()
    var accountType = addNewViewModel.accountType.collectAsState()
    val accountTypesName = AccountType.values()
    var pageState = rememberPagerState()
    var remarkinputFocus = addRecordViewModel.incomeRemarkInputState.focus.collectAsState()
    //获取状态栏和topbar高度之和
    //2024年6月30日 获取状态栏高度 topbar高度.md
    val resourceId: Int = context.resources.getIdentifier(
        "status_bar_height",
        "dimen",
        "android"
    )
    val resources = context.resources
    var topbarAndStatusBarHeight = resources.getDimensionPixelSize(resourceId)
    var imePaddingBottomValue = mainViewModel.imePaddingBottomValue.collectAsState()
    var maxImePaddingBottomValue = mainViewModel.imeMaxPaddingBottomValue.collectAsState()
    val showTopBar by remember {
        derivedStateOf {
            if (!remarkinputFocus.value) {
                true
            } else {
                (imePaddingBottomValue.value < (if (maxImePaddingBottomValue.value == 0.dp) 150.dp else maxImePaddingBottomValue.value))
            }
        }
    }
    //初始化
    LaunchedEffect(Unit) {
        if (allCats.value == null || allTitles.value == null) {
            var result = addRecordViewModel.request_getAllCatsAndTitles()
                .await()
            if (result.code < 1) {
                result.data?.let {
                    var cats = it.cats
                    var titles = it.titles
                    addRecordViewModel.flowUpdate_allCats(cats)
                    addRecordViewModel.flowUpdate_allTitles(titles)
                }
            }
        }
    }

    if (!showTopBar) {
        barStateViewModel.updateAll(
            isShowBottomBar = false,
            isStatusBarDarkIcon = true,
            statusBarColor = MaterialTheme.colorScheme.background,
            navigationBarColor = MaterialTheme.colorScheme.onPrimary,
            isNavigationBarDarkIcon = true
        )
    } else {
        barStateViewModel.updateAll(
            isShowBottomBar = false,
            isStatusBarDarkIcon = false,
            statusBarColor = Color.Transparent,
            navigationBarColor = MaterialTheme.colorScheme.onPrimary,
            isNavigationBarDarkIcon = true
        )
    }



    MyScaffoldHasTipAndLoading(
        modifier = Modifier
            .fillMaxSize()
            .width(windowWidth.dp),
        containerColor = MaterialTheme.colorScheme.surface,
        content = {
            Box {
                Box(
                    modifier = Modifier
                        .fillMaxSize(),
                    contentAlignment = Alignment.TopCenter
                ) {
                    Box(
                        modifier = Modifier
                            .height(topbarAndStatusBarHeight.dp + topbarAndStatusBarHeight.dp / 2)
                            .fillMaxWidth()
                            //限制背景图的高度
                            .clipToBounds()
                    ) {
                        //背景图
                        MyFitImage(painterResourceId = R.drawable.bg4)
                    }
                    //tab页签的内容
                    HorizontalPager(
                        modifier = Modifier
                            .fillMaxSize(),
                        state = pageState,
                        count = accountTypesName.size,
                        content = {
                            if (currentPage === 0) {
                                addNewViewModel.flowUpdate_accountType(AccountType.INCOME)
                                //输入框在这里面
                                IncomeContent(
                                    topbarAndStatusBarHeight = topbarAndStatusBarHeight,
                                    placeClick = {
                                        //myMapSelectedState.mapOpenState.value = true
                                        myMapSelectedState.showPlaceBottomSheet.value = true
                                    }
                                )
                            } else {
                                addNewViewModel.flowUpdate_accountType(AccountType.PAY)
                                PayContent(
                                    topbarAndStatusBarHeight = topbarAndStatusBarHeight
                                )
                            }
                        }
                    )
                    AnimatedVisibility(
                        //键盘等于0的时候，也可以设置图片显示，但是会有延迟，这里获取键盘的padding最大值，只要小于最大值，就显示图片，不会延迟
                        visible = showTopBar,
                        enter = slideInVertically(animationSpec = tween(durationMillis = 100)) { fullHeight -> -fullHeight },
                        exit = slideOutVertically(animationSpec = tween(durationMillis = 100)) { fullHeight -> -fullHeight }
                    ) {
                        //顶部tabRow tab的title
                        AddRecordTopBar(
                            routeViewModel = routeViewModel,
                            accountType = accountType,
                            titles = accountTypesName,
                            addNewViewModel = addNewViewModel,
                            pageState = pageState
                        )
                    }
                }
                //底部弹起的bottomSheet
                MyCustomModalBottomSheet(
                    show = myMapSelectedState.showPlaceBottomSheet.value,
                    hasNavBar = false,
                    topContent = {
                        MyTopBar(
                            title = {
                                MyText(text = "地点选择")
                            },
                            windowInsets = WindowInsets(top = 0),
                            navigationIcon = {
                                MyDownIcon(modifier = Modifier.clickable {
                                    myMapSelectedState.showPlaceBottomSheet.value = false
                                })
                            }
                        )
                    },
                    centerContent = {
                    },
                    bottomContent = {
                        MyBottomAppBar(
                            containerColor = MaterialTheme.colorScheme.surface,
                            actions = {
                                Row(modifier = Modifier.fillMaxSize()) {
                                    MyTextButton(onClick = { /*TODO*/ }) {
                                        MyText(text = "管理")
                                    }

                                    MySpacer(modifier = Modifier.weight(1f))

                                    MyTextButton(onClick = {
                                        //显示地图
                                        myMapSelectedState.mapOpenState.value = true
                                    }) {
                                        MyText(text = "新增")
                                    }
                                }
                            },
                            windowInsets = WindowInsets(
                                bottom = 0,
                                top = 0
                            )
                        )
                    },
                    backModalClickHandler = {
                        myMapSelectedState.showPlaceBottomSheet.value = false
                    }
                )


                PlaceSearch(
                    showBool = myMapSelectedState.mapOpenState.value,
                )
            }
        })
}